package mx.netbrain.dao.impl;

import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Session;

import mx.netbrain.dao.StorageDao;
import mx.netbrain.model.Storage;
import mx.netbrain.util.HibernateUtil;

public class StorageDaoImpl implements StorageDao {

	private static final Logger logger = Logger.getLogger(StorageDaoImpl.class);

	@Override
	public void save(Storage storage) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.persist(storage);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Save: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public void update(Storage storage) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(storage);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Update: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

	@Override
	public Storage findById(Integer id) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return (Storage) session.load(Storage.class, id);
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<Storage> listAll() {
		Session session = HibernateUtil.getSessionFactory().openSession();
		return session.createQuery(
				"from Storage as storage where storage.status.id = 1").list();
	}

	@Override
	public void delete(Storage storage) {
		Session session = HibernateUtil.getSessionFactory().openSession();
		try {
			session.beginTransaction();
			session.merge(storage);
			session.beginTransaction().commit();
		} catch (Exception e) {
			logger.error("Delete: " + e.getMessage());
			session.beginTransaction().rollback();
		}
	}

}
